Container的職責在於創建、配置與組裝bean,昨天我們學到了
今日將探討其他取得bean的方式與Container其他配置物件的方式
@Test
public void testDay06(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
User user= ioc.getBean(User.class);
System.out.println(user);
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user01" class="com.swj.User">
<property name="name" value="James"></property>
<property name="gender" value="male"></property>
<property name="email" value="abc@test.com.tw"></property>
</bean>
<bean id="user02" class="com.swj.User">
<property name="name" value="haha"></property>
<property name="gender" value="male"></property>
<property name="email" value="haha@test.com.tw"></property>
</bean>
</beans>
@Test
public void testDay06(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
User user= ioc.getBean(User.class);
System.out.println(user);
}
Result
@Test
public void testDay06(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
User user= ioc.getBean("user01", User.class);
System.out.println(user);
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 略 user01、user02 -->
<bean id="user03" class="com.swj.User">
<constructor-arg name="email" value="123@test.com.tw"></constructor-arg>
<constructor-arg name="name" value="kelly"></constructor-arg>
<constructor-arg name="gender" value="female"></constructor-arg>
</bean>
</beans>
public class User {
//property、getter settet略
public User(String name, String gender, String email) {
this.name = name;
this.gender = gender;
this.email = email;
System.out.println("呼叫有參建構子");
}
}
@Test
public void testDay06(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
User user= ioc.getBean("user03", User.class);
System.out.println(user);
}
Result
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 略 user01-user03 -->
<bean id="user04" class="com.swj.User" p:email="222@test" p:gender="female" p:name="karan">
</bean>
</beans>
@Test
public void testDay06(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
User user= ioc.getBean("user04", User.class);
System.out.println(user);
}
Result